package com.xiaoshu.security;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.StringUtils;

import com.xiaoshu.web.WebContext;

public class SecurityAspect {
	
	private static final String DEFAULT_TOKEN_NAME = "X-Token";
	private TokenManager tokenManager;
	private String tokenName ;
	
    public void setTokenManager(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    public void setTokenName(String tokenName) {
        if (StringUtils.isEmpty(tokenName)) {
            tokenName = DEFAULT_TOKEN_NAME;
        }
        this.tokenName = tokenName;
    }

	public Object execute(ProceedingJoinPoint pjp) throws Throwable {
		// 从切点上获取目标方法
		System.out.println("===========> 进入切面方法===============》");
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		Method method = methodSignature.getMethod();

		// 若目标方法忽略了安全性检查，则直接调用目标方法
		if (method.isAnnotationPresent(IngoreSecurity.class)) {
			return pjp.proceed();
		}

		// 从 request header 中获取当前 token
		String token = WebContext.getRequest().getHeader(tokenName);
		// 检查 token 有效性
		if(!tokenManager.checkToken(token)){
			throw new RuntimeException("Failed: The TOKEN is null or not exists..");
		}
		//调用目标方法
		return pjp.proceed();
	}

}
